#!/bin/bash

# ============================================
# 最优化 API 构建脚本
# 功能：本地编译 + Docker 构建 + 推送 + 部署
# ============================================

set -e  # 遇到错误立即退出

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查参数
if [ $# -eq 0 ]; then
    log_error "版本参数是必需的"
    echo "用法: $0 <version>"
    echo "示例: $0 v1.1.1"
    exit 1
fi

VERSION=$1
IMAGE_NAME="buding-ai"
REGISTRY="crpi-5fhtvlj50ip555mt.cn-guangzhou.personal.cr.aliyuncs.com/docker-hubes"
BINARY_NAME="ai"

log_info "开始构建 API 版本: $VERSION"

# 切换到项目根目录
PROJECT_ROOT="$(dirname "$0")/.."
cd "$PROJECT_ROOT"

log_info "当前工作目录: $(pwd)"
log_info "项目文件列表:"
ls -la

# ============================================
# 第一步：本地编译 Go 程序
# ============================================
log_info "开始编译 Go 程序..."

# 设置 Go 编译环境
export CGO_ENABLED=0
export GOOS=linux
export GOARCH=amd64
export GO111MODULE=on
export GOPROXY=https://goproxy.cn,direct

# 清理旧的二进制文件
rm -f "$BINARY_NAME"

# 编译（带优化和时间统计）
log_info "编译参数: CGO_ENABLED=$CGO_ENABLED GOOS=$GOOS GOARCH=$GOARCH"
start_time=$(date +%s)

if ! go build -ldflags "-s -w -X main.version=$VERSION -X main.buildTime=$(date -u +%Y-%m-%dT%H:%M:%SZ)" -o "$BINARY_NAME" main.go; then
    log_error "Go 编译失败"
    exit 1
fi

end_time=$(date +%s)
compile_duration=$((end_time - start_time))

log_success "Go 编译完成，耗时: ${compile_duration}s"
log_info "二进制文件信息:"
ls -lh "$BINARY_NAME"
file "$BINARY_NAME"

# ============================================
# 第二步：构建 Docker 镜像
# ============================================
log_info "开始构建 Docker 镜像..."

# 构建镜像（启用 BuildKit 缓存）
export DOCKER_BUILDKIT=1

start_time=$(date +%s)

if ! docker build \
    --build-arg BUILDKIT_INLINE_CACHE=1 \
    --cache-from "$IMAGE_NAME:latest" \
    -t "$IMAGE_NAME:$VERSION" \
    -t "$IMAGE_NAME:latest" \
    .; then
    log_error "Docker 镜像构建失败"
    rm -f "$BINARY_NAME"
    exit 1
fi

end_time=$(date +%s)
build_duration=$((end_time - start_time))

log_success "Docker 镜像构建完成，耗时: ${build_duration}s"

# 显示镜像信息
log_info "镜像信息:"
docker images | grep "$IMAGE_NAME" | head -5

# 清理本地二进制文件
rm -f "$BINARY_NAME"

# ============================================
# 第三步：镜像标记和推送
# ============================================
log_info "开始推送镜像到阿里云容器镜像服务..."

# 标记镜像
docker tag "$IMAGE_NAME:$VERSION" "$REGISTRY/$IMAGE_NAME:$VERSION"
docker tag "$IMAGE_NAME:latest" "$REGISTRY/$IMAGE_NAME:latest"

log_success "镜像标记完成"

# 推送镜像
start_time=$(date +%s)

log_info "推送版本镜像: $REGISTRY/$IMAGE_NAME:$VERSION"
if ! docker push "$REGISTRY/$IMAGE_NAME:$VERSION"; then
    log_error "版本镜像推送失败"
    exit 1
fi

log_info "推送最新镜像: $REGISTRY/$IMAGE_NAME:latest"
if ! docker push "$REGISTRY/$IMAGE_NAME:latest"; then
    log_error "最新镜像推送失败"
    exit 1
fi

end_time=$(date +%s)
push_duration=$((end_time - start_time))

log_success "镜像推送完成，耗时: ${push_duration}s"

# ============================================
# 第四步：Kubernetes 部署更新
# ============================================
log_info "开始更新 Kubernetes 部署..."

# 更新部署
if ! kubectl set image deployment/buding-ai buding-ai="$REGISTRY/$IMAGE_NAME:$VERSION" -n work; then
    log_error "Kubernetes 部署更新失败"
    exit 1
fi

log_success "Kubernetes 部署更新命令执行成功"

# 等待部署完成
log_info "等待部署滚动更新完成..."
if ! kubectl rollout status deployment/buding-ai -n work --timeout=300s; then
    log_error "部署滚动更新超时或失败"
    log_info "查看部署状态:"
    kubectl get pods -n work -l app=buding-ai
    kubectl describe deployment/buding-ai -n work
    exit 1
fi

log_success "部署滚动更新完成"

# ============================================
# 第五步：验证部署
# ============================================
log_info "验证部署状态..."

# 显示 Pod 状态
log_info "当前 Pod 状态:"
kubectl get pods -n work -l app=buding-ai -o wide

# 显示服务状态
log_info "服务状态:"
kubectl get svc -n work -l app=buding-ai

# 显示部署历史
log_info "部署历史:"
kubectl rollout history deployment/buding-ai -n work

# ============================================
# 构建完成总结
# ============================================
total_duration=$((compile_duration + build_duration + push_duration))

echo ""
log_success "=== API 构建完成 ==="
echo -e "${GREEN}版本:${NC} $VERSION"
echo -e "${GREEN}镜像:${NC} $REGISTRY/$IMAGE_NAME:$VERSION"
echo -e "${GREEN}编译耗时:${NC} ${compile_duration}s"
echo -e "${GREEN}构建耗时:${NC} ${build_duration}s"
echo -e "${GREEN}推送耗时:${NC} ${push_duration}s"
echo -e "${GREEN}总耗时:${NC} ${total_duration}s"
echo -e "${GREEN}部署状态:${NC} 已更新到 Kubernetes"
echo ""

# 可选：清理旧镜像（保留最近3个版本）
log_info "清理旧的本地镜像..."
docker images "$IMAGE_NAME" --format "table {{.Repository}}:{{.Tag}}\t{{.CreatedAt}}" | tail -n +2 | head -n -3 | awk '{print $1}' | xargs -r docker rmi 2>/dev/null || true

log_success "API 构建和部署流程全部完成！"
